package pri.zjy.interview;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zhangjy
 * @description
 * @date 2025/5/29 17:27
 */
public class Test4 {

    public static void main(String[] args) {
        int[] nums = {0, 1, 5, 4, 2};
        int target = 3;

        int[] twoSum = getTwoSum(nums, target);
        for (int i = 0; i < twoSum.length; i++) {
            System.out.println(twoSum[i]);
        }
    }

    /**
     * 两数之和，整数数组，和target；找到两者之和为target的元素下标
     *
     * 要求时间复杂度低
     */
    public static int[] getTwoSum(int[] nums, int target) {
        if (nums.length == 0) return new int[]{};

        // 遍历同时查找目标元素
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int num = target - nums[i];
            // 找到
            if (map.containsKey(num)) {
                Integer i1 = map.get(num);
                return new int[]{i1, i};
            }
            // 找不到
            map.put(nums[i], i);
        }

        return new int[]{};
    }

}
